package com.geezdata.cps.cqrs.event.publish.impl;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.geezdata.cps.cqrs.event.Event;
import com.geezdata.cps.cqrs.event.annotation.EventPublisher;
import com.geezdata.cps.cqrs.event.enums.EventSource;
import com.geezdata.cps.cqrs.event.listener.Listener;
import com.geezdata.cps.cqrs.event.listener.container.ListenerContainer;
import com.geezdata.cps.cqrs.event.publish.AbstractPublisher;


@EventPublisher(source = EventSource.DEFAULT)
public class DefaultPublisher extends AbstractPublisher {

    private static Logger logger = LoggerFactory.getLogger(DefaultPublisher.class);

    public DefaultPublisher(ListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    @Override
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public <T> void publish(Event<T> event) {
        
		List<Listener> listeners = listenerContainer.getListeners(event.getClass());
        if (listeners != null) {
            for (Listener listener : listeners) {
                try {
                    listener.onEvent(event);
                } catch (Exception e) {
                    logger.error("DefaultPublisher catch exception. {}", e);
                }
            }
        }
    }
}
